package TestSparkConversionOperator.KeyValuePairRDD;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.PairFunction;
import scala.Tuple2;

import java.util.Arrays;
import java.util.List;

public class SparkGroupByKey {
    public static void main(String[] args) {
        /**
         * 按照key进行分组，返回一个新的键值对RDD。
         * 新的RDD的key和旧的RDD的key一样，值是相同key的value的集合（Iterable对象）。
         */
        SparkConf sparkConf = new SparkConf().setAppName("SparkGroupByKey").setMaster("local");
        JavaSparkContext sc = new JavaSparkContext(sparkConf);
        List<String> data = Arrays.asList("2021-10,47", "2020-11,47","2021-10,97");
        JavaRDD<String> rdd1 = sc.parallelize(data);

        JavaPairRDD<String, String> pairRDD = rdd1.mapToPair(new PairFunction<String, String, String>() {
            @Override
            public Tuple2<String, String> call(String s) throws Exception {

                return new Tuple2<>(s.split(",")[0], s);
            }
        });
        JavaPairRDD<String, Iterable<String>> stringIterableJavaPairRDD = pairRDD.groupByKey();
        System.out.println(stringIterableJavaPairRDD.collect());

    }
}
